package pl.un4giv3n.mightvsmagic.jobs;

import java.util.Date;
import java.util.List;

import javax.mail.NoSuchProviderException;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;
import pl.un4giv3n.mightvsmagic.utils.MailSender;

public class UnblockPlayersTask {
	private static final Logger LOG = Logger.getLogger(UnblockPlayersTask.class.getName());
	private EntityManager em;
	
	public UnblockPlayersTask(EntityManager entityManager) {
		this.em = entityManager;
	}

	@SuppressWarnings("unchecked")
	public void unblockPlayers() {
		Query query = em.createNamedQuery("find.all.blocked.users");
		List<User> blockedUsers = query.getResultList();
		Date now = new Date();
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		for (User user : blockedUsers) {
			Date blockedUntil = user.getBlockedUntil();
			if(blockedUntil != null && blockedUntil.before(now)){
				user.setBlocked(false);
				user.setBlockedUntil(null);
				user.setBlockReason(null);
				try {
					MailSender.send(user.getEmail(), MailSender.UNBLOCK_USER_SUBJECT, MailSender.getUnBlockUserMessage(user, user.getId()+"", "autoadmin", "Automatyne odblokowanie po okreslonym czasie"));
				} catch (NoSuchProviderException e) {
					LOG.error(e.getMessage(),e);
				}
				UserActivity adminActivity = ActivityLogUtil.createActivity(ActivityType.ADMIN_UNBAN_PLAYER, user.getId()," Odblokowanie gracza: "+ user.toString()+", powód: Automatyne odblokowanie po okreslonym czasie");
				em.persist(adminActivity);
				em.merge(user);
			}
		}
		em.flush();
		transaction.commit();
	}
}
